<?php
/*
+ ---------------------------------------------------------------------- +
| e107Shop - An e-commerce plugin for the e107 content management system |
|                                                                        |
| ByOrder Europe 2007-2009                                               |
| http://e107shop.com                                                    |
| pbielen@gmail.com                                                      |
|                                                                        |
| Released under the terms and conditions of the LGPL                    |
+ ---------------------------------------------------------------------- +
*/

require_once("../../class2.php");
require_once("library/api.php");

function e107shop_generate_invoice($theorder){
    global $e107shop_db_name, $shop_settings, $tp;
    $sql = new db();
    $sql2 = new db();
    $order['number'] = $tp->toDB($theorder);
    $order['date'] = e107shop_get_order_date($tp->toDB($order['number']));
    $order['paymentmethod'] = e107shop_get_payment_method($order['number']);
    $order['customerinfo'] = e107shop_get_cust_info($theorder);
    $tblProducts = new db;
    $i=1;
    $total = $sql->db_Select($e107shop_db_name['orders'], "*", "order_number='".$order["number"]."'", "default", FALSE);
    $gateway = "";
    $customFields = array();
    $counter = 0;
    while($row = $sql->db_Fetch(MYSQLI_ASSOC)){
        $customFields = array($row['field1'], $row['field2'], $row['field3'], $row['field4'], $row['field5'], 
        $row['field6'], $row['field7'], $row['field8'], $row['field9'], $row['field10'], 
        $row['field11'], $row['field12'], $row['field13'], $row['field14'], $row['field15'], 
        $row['field16'], $row['field17'], $row['field18'], $row['field19'], $row['field20']);
        $coupon = $row["coupon"];
        $line_product_price = $row["sale_price"];
        $gateway = $row["gateway"];
        $product_total_price = $line_product_price * $row['quantity'];
        $product_price += $line_product_price * $row['quantity'];
        if($shop_settings["postage_method"] == "3"){
            $quantity += $row['quantity'];
            // always reset the postage price, cause we only want one calculation
            // with the exact amount of quantity
            $postage_price = e107shop_get_postage_price($row["productID"], 
            $quantity, e107shop_get_cust_info($theorder, "region"));
        } else {
            $postage_price += e107shop_get_postage_price($row["productID"], $row['quantity']);
        }
        
        $productdesc = e107shop_get_product_field($row["productID"], "product_name");
        // Display the choosen options here
        $options = explode("|", $row["option"]);
        if (is_array($options)) {
            if ($options['0']) $productdesc .= "<br /><div style='height: 5px;'></div><b>".lan_global_options."</b>";
            foreach ($options as $value) {
                if ($sql2->db_Select($e107shop_db_name['product_options'], "*", "ID='".$value."'")) {
                    while ($row2=$sql2->db_Fetch()) {
                        $productdesc .= "<br />".$row2["option_group"].": ".$row2['optname'];
                    }
                }
            }
        }
        
        // now check if the product is customized by the customer
        $firstRecord = 0;
        if ($customFields[0] != '') {
            // retrieve the names of the custom product fields
            $tblProducts->db_Select($e107shop_db_name['products'], "*", "ID='".$row['productID']."'");
            $tblProductsRow = $tblProducts->db_Fetch();
            $customProductFields = array($tblProductsRow['fname_1'], $tblProductsRow['fname_2'], $tblProductsRow['fname_3'], $tblProductsRow['fname_4'], $tblProductsRow['fname_5'], 
            $tblProductsRow['fname_6'], $tblProductsRow['fname_7'], $tblProductsRow['fname_8'], $tblProductsRow['fname_9'], $tblProductsRow['fname_10'], 
            $tblProductsRow['fname_11'], $tblProductsRow['fname_12'], $tblProductsRow['fname_13'], $tblProductsRow['fname_14'], $tblProductsRow['fname_15'], 
            $tblProductsRow['fname_16'], $tblProductsRow['fname_17'], $tblProductsRow['fname_18'], $tblProductsRow['fname_19'], $tblProductsRow['fname_20']);
            $productdesc .= "<br /><br />".lan_custom_fields;
            foreach ($customFields as $value) {
                if ($value != '') $productdesc .= "\r\n".$customProductFields[$firstRecord].": ".$value;
                $firstRecord += 1; 
            }
        }
        
        if ($shop_settings['tax_inc'] == 1) {
            $line_product_price = roundfix(e107shop_calculate_excl($line_product_price, $shop_settings['tax_rate']), 2);
            $product_total_price = roundfix(e107shop_calculate_excl($product_total_price, $shop_settings['tax_rate']), 2);
        } else {
            $line_product_price = roundfix($line_product_price, 2);
            $product_total_price = roundfix($product_total_price, 2);
        }

        //
        // Calculate the total of the cart
        //
        $line[] = array( 
            lan_invoice_ref             => $i,
            lan_global_product_name     => $productdesc,
            lan_global_quantity         => $row["quantity"],
            lan_global_price_per_item   => html_entity_decode($shop_settings["currency_symbol"], ENT_COMPAT, "UTF-8").e107shop_get_numformat($line_product_price),
            lan_global_total_price      => html_entity_decode($shop_settings["currency_symbol"], ENT_COMPAT, "UTF-8").e107shop_get_numformat($product_total_price)
        );
        $i++;
        $counter++;
    }
    cachevars('orderlines', $line);
    if ($shop_settings['tax_inc'] == 1) $product_price = roundfix(e107shop_calculate_excl($product_price, $shop_settings['tax_rate']), 2);
    // Set and Check the coupon amount
    $coupon_amount = 0;
    if($coupon) {
        $coupon_amount = e107shop_apply_coupon($product_price, $coupon);
        $midtotal = $product_price - $coupon_amount;
    }
    $postage_price = roundfix($postage_price, 2);
    $subtotal = roundfix((($product_price - $coupon_amount) + $postage_price), 2);
    $tax = roundfix(e107shop_calculate_tax($subtotal, $shop_settings['tax_rate']), 2);
    $total = $subtotal + $tax;
    $extraCost = e107shop_calculate_extra_payment($gateway, $total, $extraPaymentInfo);
    
    $order['product_price'] = $product_price;
    $order['coupon_amount'] = $coupon_amount;
    $order['postage_price'] = $postage_price;
    $order['tax'] = $tax;
    $order['subtotal'] = $subtotal;
    $order['total'] = $total;
    $order['theorder'] = $theorder;
    $order['gateway'] = $gateway;
    $order['extrapaymentinfo'] = $extraPaymentInfo;
    $order['extracost'] = $extraCost;
    
    cachevars('orderinfo', $order);

    /*$pdf->addCadreEurosFrancs($product_price, $coupon_amount, $postage_price, $tax, $subtotal, $total, $theorder, $gateway, $extraPaymentInfo, $extraCost);*/
    require_once("shortcodes/invoice_shortcodes.php");
    if (file_exists(THEME."e107shop_invoice_template.php")) require_once(THEME."e107shop_invoice_template.php");
    else require_once("templates/invoice_template.php");
    echo $tp->parseTemplate($INVOICE_TEMPLATE, FALSE, $invoice_shortcodes);
}

if(ADMIN || e107shop_get_user_for_order($tp->toDB($_GET["o"]), USERNAME)==1){
    //Because we don't want to show the website layout around our invoice, we create our own definition of the page
    header("Content-type: text/html; charset=".CHARSET, true);
    echo (defined("STANDARDS_MODE") ? "" : "<?xml version='1.0' encoding='".CHARSET."' "."?".">\n")."<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
    echo "<html xmlns='http://www.w3.org/1999/xhtml'".(defined("TEXTDIRECTION") ? " dir='".TEXTDIRECTION."'" : "").(defined("CORE_LC") ? " xml:lang=\"".CORE_LC."\"" : "").">
            <head>
            <meta http-equiv='content-type' content='text/html; charset=".CHARSET."' />";
    echo (defined("CORE_LC")) ? "<meta http-equiv='content-language' content='".CORE_LC."' />\n" : "";
    echo "<title>".SITENAME.(defined("e_PAGETITLE") ? ": ".e_PAGETITLE : (defined("PAGE_NAME") ? ": ".PAGE_NAME : ""))."</title>\n";
    echo "</head>\n<body>\n";
    // display the invoice
    e107shop_generate_invoice($tp->toDB($_GET["o"]));
    // close the page
    echo "</body></html>";
} else {
    require_once(HEADERF);
    if (file_exists(THEME."e107shop_printable_order_template.php")) require_once(THEME."e107shop_printable_order_template.php");
    else require_once('templates/printable_order_template.php');
    $ns->tablerender(lan_global_status, $tp->parseTemplate($PRINTABLE_ORDER_NOACCESS_TEMPLATE));
    if (!USER) {
        $ns->tablerender(lan_no_perms_to_howtofix, $tp->parseTemplate($PRINTABLE_ORDER_FIXACCESS_TEMPLATE));
        require_once('../../languages/'.e_LANGUAGE.'/lan_login.php');
        require_once('../../login.php');    
    }
    require_once(FOOTERF);
}

function e107shop_store_address($theorder) {
    global $e107shop_db_name, $tp;
    $theorder = $tp->toDB($theorder);
    $sql = new db;

    $sql->db_Select($e107shop_db_name['settings'], "*");
    while($row = $sql->db_Fetch())
    {
        $staddress .= $row["store_address1"];
        $staddress .= "\n";
        $staddress .= $row["store_address2"];
        $staddress .= "\n";
        $staddress .= $row["store_address3"];
        $staddress .= "\n";
        $staddress .= $row["store_address4"];
    }
    return $staddress;
}
